package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.service.TransferService;

/**
 * @author 应癫
 */
public class TransferServiceImpl implements TransferService {

    //1. 通过new关键字实例化accountDao
    //private AccountDao accountDao = new JdbcAccountDaoImpl();

    //2. 解决new关键字创建实例问题,从Ioc容器中获取对象
    //private AccountDao accountDao = (AccountDao) BeanFactory.getBean("accountDao");

    //3. 存在硬编码问题,最理想的状态是直接定义,使用set方法或构造方法注入
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {

        //显然使用代码直接控制,业务层的事务控制不太理想
        //使用动态代理实现aop思想,控制业务层的事务

        /*try {
            //1. 关闭事务自动提交,也就是开启事务
            TransactionManger.getInstance().closeAutoCommit();*/

        Account from = accountDao.queryAccountByCardNo(fromCardNo);
        Account to = accountDao.queryAccountByCardNo(toCardNo);

        from.setMoney(from.getMoney() - money);
        to.setMoney(to.getMoney() + money);

        accountDao.updateAccountByCardNo(to);
        //制造异常
        //int i = 1 / 0;
        accountDao.updateAccountByCardNo(from);

            /*//2. 提交事务
            TransactionManger.getInstance().commit();
        } catch (Exception e) {
            //打印日志
            e.printStackTrace();
            //3. 回滚事务
            TransactionManger.getInstance().rollback();
            //将异常抛出,以便上层知道出现什么错误
            throw e;
        }*/

    }
}
